package edu.nuc.ahm.juc;


// 基本的卖票例子

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
* lock 三部曲
* 1. new ReentrantLock
* 2. lock trycatch finally
* 3. unlock
*  和 synchronized 的区别
*
* */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        // 并发 ： 多线程操作同一个资源类
        Ticket ticket = new Ticket();

        new Thread(
                ()->{
                    for (int i = 0; i < 60; i++) {
                        ticket.sale();
                    }
                }
        ).start();

        new Thread(
                ()->{
                    for (int i = 0; i < 60; i++) {
                        ticket.sale();
                    }
                }
        ).start();

        new Thread(
                ()->{
                    for (int i = 0; i < 60; i++) {
                        ticket.sale();
                    }
                }
        ).start();

    }
}

// OOP 编程
class Ticket2{
    // 属性 方法
    private int num = 50;

    Lock lock = new ReentrantLock();

    // 卖票
    public void sale(){
        lock.lock();

        try {
            if (num>0){
                System.out.println(Thread.currentThread().getName()+"卖出了"+ (num--)+"票，剩余："+num);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); // 解锁
        }
    }


}



